﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Kokomo.IO
{
	public abstract class BlockStream : Stream
	{
		//public Queue<byte[]> Blocks { get; private set; }

		public BlockStream()
		{
			//this.Blocks = new Queue<byte[]>();
		}

		protected byte[] CurrentBlock { get; private set; }
		protected int CurrentOffset { get; private set; }

		protected abstract byte[] GetNextBlock();

		//public void AddBlock(byte[] block)
		//{
		//    ThrowHelper.CheckNullArgument("block", block);
		//    lock (this.Blocks)
		//    {
		//        this.Blocks.Enqueue(block);
		//    }
		//}

		public override bool CanRead
		{
			get { return true; }
		}

		public override bool CanSeek
		{
			get { return false; }
		}

		public override bool CanWrite
		{
			get { return false; }
		}

		public override void Flush()
		{
			throw new NotImplementedException();
		}

		public override long Length
		{
			get { throw new NotImplementedException(); }
		}

		public override long Position
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			int bytesCopied = 0;
			while ((count > 0))
			{
				if ((this.CurrentBlock == null)
					|| ((this.CurrentOffset >= this.CurrentBlock.Length)))
				{
					this.CurrentBlock = this.GetNextBlock();
					if (this.CurrentBlock == null)
					{
						break;
					}
					this.CurrentOffset = 0;
				}

				int copyLength = Math.Min(count, this.CurrentBlock.Length - this.CurrentOffset);
				Array.Copy(this.CurrentBlock, this.CurrentOffset, buffer, offset, copyLength);

				count -= copyLength;
				this.CurrentOffset += copyLength;
				offset += copyLength;
				bytesCopied += copyLength;
			}

			return bytesCopied;
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotImplementedException();
		}

		public override void SetLength(long value)
		{
			throw new NotImplementedException();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			throw new NotImplementedException();
		}
	}
}
